import React, { FC, ReactElement, useCallback, useEffect, useMemo } from 'react'

import { connect } from 'react-redux'
import { Dispatch } from 'redux'

import { NavLink } from 'react-router-dom'

import { INewsList, INewsListState, IPayLoad, NewItem } from '../../typings/interface'

import Header from 'Components/Header'
import NewsList from 'Components/NewsList'
import TabMenu from 'Components/TabMenu'
import PageLoading from 'Components/PageLoading'

import style from './index.scss'
import { init } from '../../store/actions'

import { useLocalStorage } from '../../hooks/useLocalStorage'
import useFetchNewsListApi from '../../hooks/useFetchNewsApi'

interface IProps {
  addData: (data: IPayLoad) => void
  newsListState: INewsList[]
}

// Home 首页 组件
const Home: FC<IProps> = ({ addData, newsListState }): ReactElement => {
  //
  useLocalStorage('newsListState', newsListState)

  const [{ isLoading, isError, search }, setSearch, setIsLoading] = useFetchNewsListApi(
    useCallback((data) => {
      setTimeout(() => {
        addData(data)
        setIsLoading(false)
      }, 1500)
    }, []),
    useCallback((fetchData: (search: string) => void, search: string | undefined, localData?: INewsList[]) => {
      if (!localData) {
        fetchData(search!)
        return
      }
      !localData.find((item) => item.newsType === search) && fetchData(search!)
    }, []),
  )

  console.log('index render')

  const headerRight = useMemo(
    () => (
      <NavLink style={{ color: '#fff' }} to={'/collection'}>
        <span className="iconfont icon-follow" />
      </NavLink>
    ),
    [],
  )

  // active tab 对应的 list
  const activeRenderList = useMemo(() => {
    console.log('memo', search)
    return newsListState && newsListState.find((item: INewsList) => item.newsType === search)
  }, [newsListState, search])

  return (
    <div className={style['home']}>
      <Header title="新闻头条" right={headerRight} />
      <TabMenu changeSearch={setSearch} />
      {isError && <div style={{ position: 'absolute', top: 81 }}>网络错误 请稍后再试!</div>}
      {isLoading ? <PageLoading /> : activeRenderList && <NewsList list={activeRenderList!} />}
    </div>
  )
}

export default connect(
  (state: INewsListState) => {
    return {
      // @ts-ignore
      newsListState: state.newsListReducer.newsListState,
    }
  },
  (dispatch: Dispatch) => ({
    addData(data: IPayLoad): void {
      dispatch(init(data))
    },
  }),
)(Home)
